//标签过滤
function escapeStr(str) {
    // 初始化一个空字符串用于存储替换后的结果
    let result = '';
    // 遍历字符串中的每个字符
    for (let i = 0; i < str.length; i++) {
        switch (str[i]) {
            case '&':
                result += '&amp;';
                break;
            case '<':
                result += '&lt;';
                break;
            case '>':
                result += '&gt;';
                break;
            case '"':
                result += '&quot;';
                break;
            case "'":
                result += '&#039;';
                break;
            default:
                // 如果不是特殊字符，直接添加到结果字符串中
                result += str[i];
        }
    }
    return result;
}
const deleteTitle = document.getElementById("delete-one-title");
const deletePrompt = document.getElementById("delete-one-prompt");
function setText(title,prompt){
    deleteTitle.innerHTML=title;
    deletePrompt.innerHTML=prompt;
}
if(document.getElementById("search-user-input")){
    window.keyWord=document.getElementById("search-user-input").value;
}
const allInputs=document.querySelectorAll('input[type=text]');
allInputs.forEach((input) => {
    input.addEventListener('change', function(e) {
        input.value = escapeStr(input.value);
    })
})
const jumpInputs = document.querySelectorAll('.jump-input');
setTimeout(() => {
    jumpInputs.forEach((input) => {input.autocomplete = 'off';input.value = '';});
},100)
//提示框
const alertBox = document.querySelector('.alert');
function showAlert(message,color) {
    alertBox.textContent = message;
    alertBox.style.color = color;
    alertBox.style.display = 'block';
    setTimeout(() => {
        alertBox.style.display = 'none';
    }, 3000);
}
// 左侧导航栏
const leftBarLi = document.querySelectorAll(".left_bar_ul li");
const mainSections = document.querySelectorAll("main");     //当跳转页面前但又点击了导航栏时，切换为block的先展示正在加载的效果
const nowActiveModule = document.getElementById("nowActiveModule").innerHTML;
leftBarLi.forEach((barLi) => {
    barLi.addEventListener("click", function () {
        const targetId = barLi.dataset.target;
        const targetMain = document.getElementById(targetId);
        leftBarLi.forEach((li) => li.classList.remove("active"));
        barLi.classList.add("active");
        mainSections.forEach((main) => main.style.display = "none");
        targetMain.style.display = "block";
        if(nowActiveModule===targetId){
        }else if (targetId === "user_manageUser_manage") {
            window.location.href = `/AdminController/users?currentPage=1&pageSize=8`;
        }else if (targetId === "hot_search") {
            window.location.href = `/AdminController/hotSearch?currentPage=1&pageSize=7`;
        }else if(targetId === "article_review") {
            window.location.href = `/AdminController/audit?currentPage=1&pageSize=8`;
        }else if(targetId === "tag_manage") {
            window.location.href = `/AdminController/tag?currentPage=1&pageSize=8`;
        }else if(targetId === "review_form") {
            window.location.href = `/AdminController/auditLog?currentPage=1&pageSize=8`;
        }
    });
});

// 二级菜单
const adminProfile = document.querySelector(".admin_profile");
const adminProfileDropdown = document.querySelector(".admin_profile_dropdown");
let dropdownTimer;
adminProfile.addEventListener("mouseenter", () => {
    clearTimeout(dropdownTimer);
    adminProfileDropdown.style.display = "block";
    setTimeout(() => {
        adminProfileDropdown.style.opacity = '1';
        adminProfileDropdown.style.transform = 'translateY(0)';
    }, 10);
});
adminProfile.addEventListener("mouseleave", () => {
    adminProfileDropdown.style.opacity = '0';
    adminProfileDropdown.style.transform = 'translateY(-10px)';
    dropdownTimer = setTimeout(() => {
        adminProfileDropdown.style.display = "none";
    }, 300);
});

// 全选用户按钮全选功能
const selectAll = document.getElementById("selectAll");
const userCheckbox = document.querySelectorAll(".userCheckbox");
if (selectAll) {
    selectAll.addEventListener("change", function () {
    userCheckbox.forEach((checkbox) => checkbox.checked = this.checked);
});}
//弹窗封装--不绑定单击响应函数,方便设置特定的点击函数
function tc_open2(targetTc,showM,flexOrblock) {
    showM.style.display = "block";
    targetTc.style.display = ""+flexOrblock;
    setTimeout(() => {
        targetTc.style.transform = "scale(1)";
    }, 10);
}

function tc_close2( targetTc,showM) {
    targetTc.style.transform = "scale(0)";
    setTimeout(() => {
        showM.style.display = "none";
        targetTc.style.display = "none";
    }, 100);
}
//用户管理模块
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,64}$/;
const emailRegex = /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/;
//编辑用户
const UDavatarInput = document.getElementById("user-avatar-edit-file");//头像输入file
const UDavatarclick = document.getElementById("user-avatar-edit-select");//头像点击
const UDavatarDafault = document.getElementById("default-avatar");//默认头像
const editUserData = document.getElementById("edit-user-d");
const showModal = document.getElementById("showModal");
const editUserBtn = document.querySelectorAll(".edit-user");
const UDnameInput = document.getElementById("user-name-edit-input");//昵称
const UDgender = document.getElementsByClassName("user-gender-edit");//性别
const UDmember = document.getElementsByClassName("user-member-set-input");//会员
const UDadmin = document.getElementsByClassName("user-admin-set-input");//管理员
const UDaddressInput = document.getElementById("user-address-edit-input");//地址
const UDintroductionInput = document.getElementById("user-introduction-edit-input");//简介
const UDemailInput = document.getElementById("user-email-edit-input");//邮箱
const UDverificed = document.getElementById("user-verified-set");//认证
const UDverifiedInput = document.getElementById("user-verified-set-input");//认证信息
const UDavatar = document.getElementById("user-avatar-edit-d2");//头像
const UDalert= document.getElementsByClassName("alert-adit");
const confirmedit = document.getElementById("confirm-edit");
const canceledit = document.getElementById("cancel-edit");
UDverificed.onchange = () => {
    if (UDverificed.checked) {
        UDverifiedInput.style.display = "block";
    }else{
        UDverifiedInput.style.display = "none";
    }
}
editUserBtn.forEach((btn) => {
    btn.onclick=(async () => {
        const row = btn.closest("tr");
        const userId = row.querySelector('td:nth-child(2)').textContent;
        try {
            const userData = await getuserdata(userId);
            await upedituserTc(userData);
            tc_open2(editUserData,showModal,"block");
            [showModal,canceledit].forEach((btn) => {
                btn.onclick=(() => {
                    tc_close2(editUserData,showModal);
                });
            });
            confirmedit.onclick=(async () => {
                const row = btn.closest("tr");
                const userId = row.querySelector('td:nth-child(2)').textContent;
                console.log(userId);
                try {
                    await judgeUserData();
                    updataUserData(userId);
                } catch (error) {
                    showAlert("修改用户信息失败","red");
                }
            });
            UDavatarclick.onclick=(()=>{        //更换头像
                UDavatarInput.click();
            });
            UDavatarInput.onchange=( () => {
                const file = UDavatarInput.files[0];
                if (file) {
                    let reader = new FileReader();
                    reader.onload = (e) => {
                        UDavatar.style.backgroundImage = `url(${e.target.result})`;
                    };
                    reader.onerror = () => {
                        showAlert("头像上传失败，请重试", "red");
                    };
                    reader.readAsDataURL(file);
                }
            });
            UDavatarDafault.onclick=(()=>{         //使用默认头像
                UDavatar.style.backgroundImage = `url(/img/default_avatar/image.png)`;
            })
        } catch (error) {
            showAlert("获取用户信息失败","red");
        }
    });
})

function getuserdata(userId) {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: `/AdminController/users/${userId}`,
            type: 'get',
            dataType: "json",
            contentType: "application/json",
            success: function (result) {
                resolve(result);
            },
            error: function () {
                reject();
            }
        })
    })
}
function upedituserTc(userData){
    return new Promise((resolve, reject) => {
        UDnameInput.value = userData.userName;
        UDaddressInput.value = userData.address;
        if(userData.introduction===""){
            UDintroductionInput.value = "这个人很懒，什么都没有留下";
        } else UDintroductionInput.value = userData.introduction;
        UDemailInput.value = userData.email;
        UDavatar.style.backgroundImage = `url('${userData.avatar}')`;
        if(userData.gender === 0) UDgender[0].checked = true;
        else UDgender[1].checked = true;
        if(userData.memberStatus === 0) UDmember[0].checked = true;
        else if(userData.memberStatus === 1) UDmember[1].checked = true;
        else UDmember[2].checked = true;
        if(userData.adminStatus === 0) UDadmin[0].checked = true;
        else UDadmin[1].checked = true;
        if(userData.verifiedStatus === 0){
            UDverificed.checked = false;
            UDverifiedInput.style.display = "none";
        } else {
            UDverificed.checked = true;
            UDverifiedInput.style.display = "block";
        }
        resolve();
    })
}
function judgeUserData(){
    return new Promise((resolve, reject) => {
        let sta = true;
        // 检查昵称输入框是否为空
        if(UDnameInput.value === ''){
            UDalert[0].style.display = "block";
            showAlert("昵称不能为空","red");
            sta = false;
        } else {
            UDalert[0].style.display = "none";
        }
        // 检查邮箱输入框是否符合要求
        if(UDemailInput.value === ''||!emailRegex.test(UDemailInput.value)){
            UDalert[2].style.display = "block";
            showAlert("邮箱格式错误","red");
            sta=false;
        }else UDalert[2].style.display = "none";
        // 检查认证状态，如果勾选认证则检查认证信息是否为空
        if(UDverificed.checked){
            if(UDverifiedInput.value === ''){
                UDalert[3].style.display = "block";
                showAlert("认证信息不能为空","red");
                sta = false;
            } else {
                UDalert[3].style.display = "none";
            }
        }
        // 根据验证结果决定是 resolve 还是 reject
        if(sta) {
            resolve();
        } else {
            reject();
        }
    })
}

function updataUserData(userId){
    let adminStatus=UDadmin[0].checked?0:1;
    let avatar = UDavatar.style.backgroundImage.replace(/url\(['"]?([^'"]+)['"]?\)/, '$1');
    let gender = UDgender[0].checked?0:1;
    let memberStatus = UDmember[0].checked?0:(UDmember[1].checked?1:2);
    let verifiedStatus = UDverificed.checked?1:0;
    let url;
    if(verifiedStatus===1){
        url=`/AdminController/users/update/${userId}?address=${UDaddressInput.value}&adminStatus=${adminStatus}&avatar=${avatar}&email=${UDemailInput.value}&flashAttributes=%7B%7D&gender=${gender}&introduction=${UDintroductionInput.value}&memberStatus=${memberStatus}&userName=${UDnameInput.value}&verificationInfo=${UDverifiedInput.value}&verifiedStatus=${verifiedStatus}`
    }else{
        url=`/AdminController/users/update/${userId}?address=${UDaddressInput.value}&adminStatus=${adminStatus}&avatar=${avatar}&email=${UDemailInput.value}&flashAttributes=%7B%7D&gender=${gender}&introduction=${UDintroductionInput.value}&memberStatus=${memberStatus}&userName=${UDnameInput.value}&verifiedStatus=${verifiedStatus}`
    }
    $.ajax({
        url: url,
        type: 'post',
        dataType: 'json',
        contentType: "application/json",
        success: function (result) {
            if(result.code>=300){
                showAlert(result.message,"red");
                return;
            }
            showAlert("修改用户信息成功","green");
            tc_close2(editUserData,showModal);
            setTimeout(() => {
                window.location.href = `/AdminController/users?currentPage=${window.currentPage}&pageSize=10&keyword=${window.keyWord}`;
            }, 500);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            let errorMessage = "修改用户信息失败";
            try {
                // 尝试解析响应的 JSON 数据
                const responseData = JSON.parse(jqXHR.responseText);
                if (responseData.message) {
                    errorMessage = responseData.message;
                }
            } catch (parseError) {
                // 解析失败，使用默认错误信息
            }
            showAlert(errorMessage, "red");
        }
    });
}

//用户权限设置
    //用户权限设置
const banPosts = document.getElementsByClassName("ban-post");        //禁言按钮元素的数组
const banPostTc = document.getElementById("ban-post-tc");                //showModal背景遮罩
const bpud = document.getElementsByClassName("bpud");                 //ban post user data////img name id
const closeBanPost = document.getElementById("close-ban-post");
const confirmBanPost = document.getElementById("confirm-ban-post");
const cancelBanPost = document.getElementById("cancel-ban-post");
const showModalBan = document.getElementById("showModal_ban");

function updataBanPost1(clickObj) {              //再弹窗开启时更新弹窗里面用户的信息
    const row = clickObj.closest("tr");
    const userId = row.querySelector('td:nth-child(2)').textContent;
    const username = row.querySelector('td:nth-child(3)').textContent;
    const profileSrc = row.querySelector('td:nth-child(5)>img').src;
    bpud[0].src = profileSrc;
    bpud[1].innerHTML = `昵称：${username}`;
    bpud[2].innerHTML = `Id：${userId}`;
}

for (let banPost of banPosts) {
    banPost.addEventListener("click", ()=>{
        const row = banPost.closest("tr");
        const userId = row.querySelector('td:nth-child(2)').textContent;
        //判断是否封禁、禁言、禁私
        const userStatus = row.querySelector('td:nth-child(10)').textContent.trim();
        document.getElementById("ban-to-post-input").checked=false;
        document.getElementById("ban-privacy-input").checked=false;
        document.getElementById("banned-input").checked=false;
        if(userStatus==="封禁"){document.getElementById("banned-input").checked=true;}
        else if(userStatus==="禁言"){document.getElementById("ban-to-post-input").checked=true;}
        else if(userStatus==="禁私"){document.getElementById("ban-privacy-input").checked=true;}
        else{
            document.getElementById("ban-to-post-input").checked=false;
            document.getElementById("ban-privacy-input").checked=false;
            document.getElementById("banned-input").checked=false;
        }
        updataBanPost1(banPost);
        tc_open2(banPostTc,showModalBan,"flex");
        [closeBanPost,cancelBanPost,showModalBan].forEach((closeTc)=>{           //×和取消关闭弹窗
            closeTc.onclick=(()=>{tc_close2(banPostTc,showModalBan)});
        })
        confirmBanPost.onclick=(async ()=>{
                try {
                    await setuserauthAll(userId,row);
                    showAlert("修改用户权限成功", "green");
                    setTimeout(()=>{
                        tc_close2(banPostTc,showModalBan);
                    },200)
                }
                catch(err) {
                    showAlert("修改用户权限失败", "red");
                }
            tc_close2(banPostTc,showModalBan);
        });
    }, false);
}
function setuserauthAll(userId,row){
    return new Promise((resolve,reject)=>{
        let isBanPost = document.getElementById("ban-to-post-input").checked?1:0;       //是否禁言
        let isPrivateMessage = document.getElementById("ban-privacy-input").checked?1:0;    //是否禁言私聊
        let isBanAccount = document.getElementById("banned-input").checked?1:0;         //是否封禁账号
        let data = JSON.stringify([
            {
                "banAccount": isBanAccount,
                "isBanned": isBanPost,
                "isPrivateMessage": isPrivateMessage,
                "userId": userId,
                "userStatusId": 0
            }
        ]);
        $.ajax({
            url: `/AdminController/users/batch-permissions`,
            type: 'post',
            dataType: "text",
            contentType: "application/json",
            data:data,
            success: function () {
                const userStatus = row.querySelector('td:nth-child(10)').getElementsByTagName("div")[0];
                userStatus.innerHTML=isBanAccount===1?"封禁":isBanPost===1?"禁言":isPrivateMessage===1?"禁私":"正常";
                userStatus.style.backgroundColor=isBanAccount===1?"rgba(255,10,10,1)":isBanPost===1?"rgba(242,164, 81,1)":isPrivateMessage===1?"rgba(242,164, 81,1)":"rgba( 56,179,148,1)";
                resolve();
            },
            error: function () {
                reject();
            }
        })
    })
}
    //批量设置用户权限
const batchSetUserAuth = document.getElementById("batch-ban-user");
const batchSetUserTc = document.getElementById("user-battch-operata");
const batchshowModal = document.getElementById("battch-operate-user-showmodel");
const confirmBatchSetUser = document.getElementById("confirm-battch-operate");
const cancelBatchSetUser = document.getElementById("cancel-battch-operate");
const bduCheck = document.querySelectorAll(".userCheckbox");
if(batchSetUserAuth){
    batchSetUserAuth.addEventListener("click", ()=>{
        tc_open2(batchSetUserTc,batchshowModal,"block");
        [cancelBatchSetUser,batchshowModal].forEach((closeTc)=>{           //×和取消关闭弹窗
            closeTc.onclick=(()=>{tc_close2(batchSetUserTc,batchshowModal)});
        });
        let setauthIds=[];
        bduCheck.forEach((bducheck)=>{
            if(bducheck.checked){
                const row = bducheck.closest("tr");
                const userId = row.querySelector('td:nth-child(2)').textContent;
                setauthIds.push(userId);
            }
        })
        confirmBatchSetUser.onclick=(async ()=>{
            try {
                await setuserauth(setauthIds);
                showAlert("修改用户权限成功", "green");
                tc_close2(batchSetUserTc,batchshowModal);
                setTimeout(()=>{
                    window.location.href = `/AdminController/users?currentPage=${window.currentPage}&pageSize=10&keyword=${window.keyWord}`;
                },200)
            }
            catch(err){
                showAlert("修改用户权限失败", "red");
            }
        })
    })
}
function setuserauth(setauthIds){
    return new Promise((resolve,reject)=>{
        let isBanPost = document.getElementById("ban-to-post-input-b").checked?1:0;       //是否禁言
        let isPrivateMessage = document.getElementById("ban-privacy-input-b").checked?1:0;    //是否禁言私聊
        let isBanAccount = document.getElementById("banned-input-b").checked?1:0;         //是否封禁账号
        let data = [];
        setauthIds.forEach((id)=>{
            data.push({
                "banAccount": isBanAccount,
                "isBanned": isBanPost,
                "isPrivateMessage": isPrivateMessage,
                "userId": id,
                "userStatusId": 0
            })
        })
        data = JSON.stringify(
            data
        )
        $.ajax({
            url: `/AdminController/users/batch-permissions`,
            type: 'post',
            dataType: "text",
            contentType: "application/json",
            data:data,
            success: function () {
                resolve();
            },
            error: function () {
                reject();
            }
        })
    })
}
//删除用户设置
const deleteUserTc = document.getElementById("delete-user-tc");     //删除用户时的弹窗
const showModalDele = document.getElementById("showModal_delete");    
const deleteUsers = document.getElementsByClassName("delete-user");     //删除用户的按钮
const closeDelete = document.getElementById("close-delete-user");
const confirmDelete = document.getElementById("confirm-delete");
const cancelDelete = document.getElementById("cancel-delete");
const deleteUserData = document.getElementsByClassName("delete-user-data");
const auth = document.getElementById("auth");
const authprompt = document.getElementById("default_user-span");
function updataBanPost(clickObj) {              //再弹窗开启时更新弹窗里面用户的信息
    return new Promise((resolve) => {
        const row = clickObj.closest("tr");
        const username = row.querySelector('td:nth-child(3)').textContent;
        const profileSrc = row.querySelector('td:nth-child(5)>img').src;
        deleteUserData[0].src = profileSrc;
        deleteUserData[1].innerHTML = `昵称：${username}`;
        confirmDelete.onclick=()=>{
            if(!auth.checked){
                showauthprompt();
            }else{
                let userId =row.querySelector('td:nth-child(2)').textContent;
                let url=`/AdminController/users/delete/${userId}?flashAttributes=%7B%7D`;
                $.ajax({
                    url:url,
                    type:'post',
                    dataType:"text",
                    contentType:"application/json",
                    success:function(){
                        showAlert("删除成功",'green');
                        auth.checked=false;
                        tc_close2(deleteUserTc,showModalDele);
                        setTimeout(() => { window.location.href=`/AdminController/users?currentPage=${window.currentPage}&pageSize=10`;},500)
                    },
                    error:function(){
                        showAlert("删除失败",'red');
                    }
                })
            }
        };
        resolve();
    });
}

[showModalDele,closeDelete,cancelDelete].forEach((closeE)=>{
    closeE.addEventListener("click",()=>{
        auth.checked=false;
        tc_close2(deleteUserTc,showModalDele);
    },false);
});

let timerAuth;
function showauthprompt(){
    clearTimeout(timerAuth);
    authprompt.style.display="block";
    timerAuth=setTimeout(() => {
        authprompt.style.display="none";
    }, 1500);
}

for (let deleteUser of deleteUsers) {
    deleteUser.addEventListener("click", async function () {
        await updataBanPost(deleteUser);
        tc_open2(deleteUserTc,showModalDele,"block");
    }, false);
}
//批量删除用户
function batchDelete(checkbox,url,tc,showModal,jumpModal){          //批量删除的函数
    //删除用户后的操作
    let deleteIds = [];
    for(let i=0;i<checkbox.length;i++){     //获取选中的用户的id
        if(checkbox[i].checked){
            const row = checkbox[i].closest("tr");
            let userId =row.querySelector('td:nth-child(2)').textContent;
            deleteIds.push(userId);
        }
    }
    if(deleteIds.length===0){
        showAlert("未选择要删除的用户",'red');
    }else{
        let url2=url;
        for(let i=0;i<deleteIds.length;i++){
            url2+=`&ids=${deleteIds[i]}`;
        }
        $.ajax({
            url:url2,
            type:'post',
            dataType:"text",
            contentType:"application/json",
            success:function(data){
                showAlert("删除成功",'green');
                tc_close2(tc,showModal);
                setTimeout(() => { window.location.href=`/AdminController/${jumpModal}?currentPage=${window.currentPage}&pageSize=10`;},500)
            },
            error:function(){
                showAlert("删除失败",'red');
            }
        })
    }
}
const bduOpen = document.getElementById("batch-delete-user");
const bdu = document.getElementById("batch-delete-user-d");
const bduClose = document.getElementById("bdu-close");
const bduConfirm = document.getElementById("bdu-confirm");
const bduCancel = document.getElementById("bdu-cancel");
const bduShowmodel = document.getElementById("showModal-batch");
if(bduOpen){
    bduOpen.addEventListener("click",()=>{tc_open2(bdu,bduShowmodel,"block")});
    [bduClose,bduCancel,bduShowmodel].forEach((close)=>{
        close.addEventListener("click",()=>{
            tc_close2(bdu,bduShowmodel);
        })
    })
    bduConfirm.addEventListener("click",()=>{
        batchDelete(bduCheck,"/AdminController/users/batch-delete?flashAttributes=%7B%7D",bdu,bduShowmodel,'users');
    })
}

//新闻审核模块
//设置全选按钮
const selectAllNews = document.getElementById("selectAllNews");
const newsCheckbox = document.querySelectorAll(".newsCheckbox");
if(selectAllNews){
    selectAllNews.addEventListener("change",function(){
        newsCheckbox.forEach((checkbox) => checkbox.checked = this.checked);
    },false);
}


//类别管理模块
//设置全选按钮
const selectAllCategory = document.getElementById("selectAllCategory");
const categoryCheckbox = document.querySelectorAll(".categoryCheckbox");
if(selectAllCategory){
    selectAllCategory.addEventListener("change",function(){
        categoryCheckbox.forEach((checkbox) => checkbox.checked = this.checked);
    },false);
}
//管理员信息设置
const showModalAdmin = document.getElementById("showModal-admin-set");      //设置弹窗的开关样式设置
const adminSetTc = document.getElementById("admin-setting-tc");
const adminSet = document.getElementById("admin-set");
const confirmSetAdmin = document.getElementById("confirm-admin-set");
const cancelSetAdmin = document.getElementById("cancel-admin-set");
adminSet.addEventListener("click",()=>{
    startProfile=adminProfileImg.style.backgroundImage.replace(/url\(['"]?([^'"]+)['"]?\)/, '$1');
    tc_open2(adminSetTc,showModalAdmin,"flex");
},false);
[showModalAdmin,cancelSetAdmin].forEach((c)=>{
    c.addEventListener("click",()=>{
        adminProfileImg.style.backgroundImage =`url(${startProfile})`;
        clearInput();
        restoreStyle();
        tc_close2(adminSetTc,showModalAdmin);
    },false);
})
confirmSetAdmin.addEventListener('click',()=>{
    tc_close2(adminSetTc,showModalAdmin);
    restoreStyle();
    //处理信息部分
    updataAdminData();
},false);

function updataAdminData(){
    const adminName = document.getElementById("admin-name-left");
    const profiles = document.querySelectorAll(".profiles");
    let newName = document.getElementById("admin-name").innerHTML;
    adminName.innerHTML=`昵称：${newName}`;
    clearInput();
    profiles.forEach((profile) => {
        const imageUrl = adminProfileImg.style.backgroundImage.replace(/url\(['"]?([^'"]+)['"]?\)/, '$1');
        profile.src = imageUrl;
        profile.onerror = () => {
            console.error('图片加载失败:', imageUrl);
            // 可以在这里添加更多的错误处理逻辑，比如显示默认图片
        };
    });
}

const adminSetName = document.getElementById("admin-set-name");             //修改昵称
const confirmAdminName = document.getElementById("confirm-amdin-name");
const adminSetNamed1 = document.getElementById("admin-name-d");
const adminSetNamed2 = document.getElementById("admin-name-d2");
const adminName = document.getElementById("admin-name");
const adminNameS = document.getElementById("admin-name-s");
adminSetName.addEventListener('click',()=>{
    adminSetNamed1.style.display="none";
    adminSetNamed2.style.display="inline-block";
},false);
confirmAdminName.addEventListener('click',()=>{
    adminSetNamed2.style.display="none";
    adminSetNamed1.style.display="inline-block";
    adminName.innerHTML=adminNameS.value;
},false);

const adminProfileSet = document.getElementById("admin-profile-shade");         //修改头像
const apf = document.getElementById("admin-profile-file");
const adminProfileImg = document.getElementById("admin-profile");
let startProfile = adminProfileImg.style.backgroundImage.replace(/url\(['"]?([^'"]+)['"]?\)/, '$1');
adminProfileSet.addEventListener("click",()=>{
    apf.click();
},false)
apf.addEventListener("change", () => {
    const file = apf.files[0];
    if (file) {
        let reader = new FileReader();
        reader.onload = (e) => {
            adminProfileImg.style.backgroundImage = `url(${e.target.result})`;
        };
        reader.readAsDataURL(file);
    }
}, false);

const toSetData = document.getElementById("to-set-data");               //设置基本信息还是设置隐私
const toSetPrivacy = document.getElementById("to-set-privacy");
const adminsetop = document.querySelectorAll(".admin-set-op");
const tosetdp = document.querySelectorAll(".to-setdp");
[toSetData,toSetPrivacy].forEach((nowSet)=>{
    nowSet.addEventListener("click",()=>{
        const targetId = nowSet.dataset.target;
        const target_obj = document.getElementById(targetId);
        tosetdp.forEach((a)=>a.classList.remove("active-sdp"));
        nowSet.classList.add("active-sdp");
        adminsetop.forEach((m) => m.style.display = "none");
        target_obj.style.display = "block";
    })
});

const changePassword = document.getElementById("change-password");      //更改密码-样式
const confirmChangePassword = document.getElementById("confirm-change-password");
const adminPasswordBox = document.getElementById("admin-password-d1");
const adminnewPbox = document.getElementById("admin-password-d2");
changePassword.addEventListener("click",()=>{
    adminPasswordBox.style.display="none";
    adminnewPbox.style.display="block";
});
confirmChangePassword.addEventListener("click",()=>{
    adminnewPbox.style.display="none";
    adminPasswordBox.style.display="block";
    clearInput();
})

const newamdinPassword = document.getElementById("admin-newpassword");          //更改密码-小眼睛
const newamdinPasswordT = document.getElementById("admin-newpasswordT");
const passwordEye1 = document.getElementById('new-password-eye1');
const passwordEye2 = document.getElementById("new-password-eye2");
function showpassword(eye,passwordinp){
    if(eye.classList.contains('icon-bukejian')){
        eye.classList.replace('icon-bukejian','icon-kejian');
        passwordinp.type="text";
    }else{
        eye.classList.replace('icon-kejian','icon-bukejian');
        passwordinp.type="password";
    }
}   
passwordEye1.addEventListener("click",()=>{
    showpassword(passwordEye1,newamdinPassword);
},false);
passwordEye2.addEventListener("click",()=>{
    showpassword(passwordEye2,newamdinPasswordT);
},false);


//添加用户
function addUserInputClear(){
    document.getElementById("avatarPreview").style.backgroundImage="";
    document.getElementById("address").value="";
    document.getElementById("isAdmin").checked=false;
    document.getElementById("bio").value="";
    document.getElementById("genderMale").checked=true;
    document.getElementById("email").value="";
    document.getElementById("password").value="";
    document.getElementById("nickname").value="";
    document.getElementById("certificationInput").value="";
    document.getElementById("isCertified").checked=false;
}
const addUser = document.getElementById("add-user");
const addUserS = document.getElementById("showModal-addUser");
const addUserTc = document.getElementById("userFormModal");
const addUserConfirm = document.getElementById("saveBtn");
const addUserCancel = document.getElementById("cancelBtn");
if(addUser){
    addUser.addEventListener("click",()=>{
        addUserInputClear();
        document.getElementById("avatarPreview").style.backgroundImage=`url("/img/default_avatar/image.png")`;
        tc_open2(addUserTc,addUserS,"block");
    });
}
[addUserCancel,addUserS].forEach((c)=>{
    c.addEventListener("click",()=>{
        tc_close2(addUserTc,addUserS);
        addUserInputClear();
    })
})
function showerror(element){
    element.style.display="block";
}
const nicknameError  = document.getElementById("nicknameError");
const addressError = document.getElementById("addressError");
const emailError = document.getElementById("emailError");
const passwordError = document.getElementById("passwordError");
const certificationError = document.getElementById("certificationError");

// 获取输入框元素
const nicknameInput = document.getElementById("nickname");
const addressInput = document.getElementById("address");
const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("password");
const certificationInput = document.getElementById("certificationInput");
const isCertifiedCheckbox = document.getElementById("isCertified");

// 定义隐藏错误信息的函数
function hideError(errorElement) {
    errorElement.style.display = "none";
}

// 为输入框添加 oninput 事件监听
nicknameInput.addEventListener("input", () => {
    if (nicknameInput.value !== "") {
        hideError(nicknameError);
    }
});
addressInput.addEventListener("input", () => {
    if (addressInput.value !== "") {
        hideError(addressError);
    }
});
emailInput.addEventListener("input", () => {
    if (emailRegex.test(emailInput.value)) {
        hideError(emailError);
    }
});
// 认证输入框和复选框的事件监听
isCertifiedCheckbox.addEventListener("change", () => {
    if (!isCertifiedCheckbox.checked) {
        hideError(certificationError);
    }
});
certificationInput.addEventListener("input", () => {
    if (!isCertifiedCheckbox.checked || certificationInput.value !== "") {
        hideError(certificationError);
    }
});
addUserConfirm.addEventListener("click",()=>{
    let address = document.getElementById("address").value;
    let adminStatus = document.getElementById("isAdmin").checked?1:0;
    let avatar = document.getElementById("avatarPreview").style.backgroundImage.replace(/url\(['"]?([^'"]+)['"]?\)/, '$1');
    let createTime = "";
    let email = document.getElementById("email").value;
    let followerCount = 0;
    let gender = document.getElementById("genderMale").checked?0:1;
    let introduction = document.getElementById("bio").value === "" ? "这个人很懒，什么都没有留下" : document.getElementById("bio").value;
    let likeCount = 0;
    let memberStatus = 0;
    let passWord = document.getElementById("password").value;
    let prizeCount = 0;
    let userId = 0;
    let userName = document.getElementById("nickname").value;
    let verificationInfo = document.getElementById("certificationInput").value;
    let verifiedStatus = document.getElementById("isCertified").checked?1:0;
    let userData = JSON.stringify({address: address, adminStatus: adminStatus, avatar: avatar, createTime: createTime, email: email, followerCount: followerCount, gender: gender, introduction: introduction, likeCount: likeCount, memberStatus: memberStatus, passWord: passWord, prizeCount: prizeCount, userId: userId, userName: userName, verificationInfo: verificationInfo, verifiedStatus: verifiedStatus
    });
    if(userName === ""){
        showerror(nicknameError);
        return;
    }else if(address === ""){
        showerror(addressError);
        return;
    }else if(verifiedStatus === 1 && verificationInfo === ""){
        showerror(certificationError);
        return;
    }else if(!emailRegex.test(email)){
        showerror(emailError);
        return;
    }
    $.ajax({
        url: "/AdminController/users/add?flashAttributes=%7B%7D",
        type: "POST",
        contentType: "application/json",
        dataType: "text",
        data: userData,
        success: function (response) {
            showAlert("添加成功","green");
            tc_close2(addUserTc,addUserS);
            setTimeout(() => {
                window.location.href = `/AdminController/users?currentPage=${window.currentPage}&pageSize=10&keyword=${window.keyWord}`;
            }, 500);
            addUserInputClear();
        },
        error: function (data) {
            showAlert("邮箱以注册或昵称重复","red");
        }
    });
});
// 头像预览功能
function previewAvatar(input) {
    const preview = document.getElementById('avatarPreview');
    const errorElement = document.getElementById('avatarError');
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.style.backgroundImage = `url('${e.target.result}')`;
            hideError(errorElement, input);
        }
        reader.readAsDataURL(input.files[0]);
    }
}
// 控制认证输入框显示隐藏
function toggleCertificationInput(checkbox) {
    const content = document.getElementById('certificationContent');
    if (checkbox.checked) {
        content.classList.add('visible');
    } else {
        content.classList.remove('visible');
        hideError(document.getElementById('certificationError'), document.getElementById('certificationInput'));
    }
}

//标签管理
    //删除标签
const deleteOneTc = document.getElementById("delete-one");
const deleteOneShowmodal = document.getElementById("delete-one-showmodal");
const deleteOneConfirm = document.getElementById("confirm-delete-one");
const deleteOneCancel = document.getElementById("cancel-delete-one");
const tagDelete = document.querySelectorAll(".category-delete");
tagDelete.forEach((tag) => {
    tag.addEventListener("click", (e) => {
        setText("删除标签","确定删除该标签吗？")
        tc_open2(deleteOneTc, deleteOneShowmodal, "block");
        [deleteOneCancel,deleteOneShowmodal].forEach((closeTc)=>{
            closeTc.onclick=(()=>{
                tc_close2(deleteOneTc,deleteOneShowmodal);
            })
        })
        deleteOneConfirm.onclick=()=>{
            const row = e.target.closest("tr");
            const tagId = row.querySelector('td:nth-child(2)').textContent;
            window.keyWord = document.getElementById("search-tag").value;
            $.ajax({
                url: `/AdminController/tag/delete/${tagId}`,
                type: "POST",
                dataType: "text",
                contentType: "application/json",
                success: function () {
                    showAlert("删除成功", "green");
                    tc_close2(deleteOneTc, deleteOneShowmodal);
                    setTimeout(() => {
                        window.location.href=`/AdminController/tag?keyword=${window.keyWord}`;
                    },300)
                },
                error: function (data) {
                    showAlert("删除失败", "red");
                }
            })
        }
    })
})
//批量删除标签
const batchDeleteTag = document.getElementById("batch-delete-category");
if(batchDeleteTag)batchDeleteTag.onclick=()=>{
    let deleteIds = [];
    categoryCheckbox.forEach((checkbox)=>{
        if(checkbox.checked){
            const row = checkbox.closest("tr");
            let tagId =row.querySelector('td:nth-child(2)').textContent;
            deleteIds.push(tagId);
        }
    })
    setText("删除标签","确定删除这些标签吗？")
    tc_open2(deleteOneTc, deleteOneShowmodal, "block");
    [deleteOneCancel,deleteOneShowmodal].forEach((closeTc)=>{
        closeTc.onclick=(()=>{
            tc_close2(deleteOneTc,deleteOneShowmodal);
        })
    })
    deleteOneConfirm.onclick=()=>{
        let url2=`/AdminController/tag/deleteBatchTag?`;
        for(let i=0;i<deleteIds.length;i++){
            if(i===0){
                url2+=`tagIds=${deleteIds[i]}`;
            }else{
                url2+=`&tagIds=${deleteIds[i]}`;
            }
        }
        if(deleteIds.length===0){
            showAlert("未选择要删除的标签",'red');
            return;
        }
        window.keyWord = document.getElementById("search-tag").value;
        $.ajax({
            url:url2,
            type:'POST',
            dataType: "text",
            contentType: "application/json",
            success: function (response) {
                showAlert("删除成功", "green");
                tc_close2(deleteOneTc, deleteOneShowmodal);
                setTimeout(() => {
                    window.location.href=`/AdminController/tag?keyword=${window.keyWord}`;
                },300)
            },
            error: function (data) {
                showAlert("删除失败", "red");
            }
        })
    }
}


//标签添加
const addTagTc = document.getElementById("add-tag-tc");
const addTagShowmodal = document.getElementById("add-tag-showModal");
const addTagclose = document.getElementById("add-tag-close");
const addTagConfirm = document.getElementById("add-tag-confirm");
const addTagCancel = document.getElementById("add-tag-cancel");
const addTagName = document.getElementById("tag-name");
const addTagInstrotiction = document.getElementById("tag-instrotiction");
const addTagIsHidden = document.getElementById("tag-ishidden");
const addTag = document.getElementById("add-category-btn");
const addTagNameWarn = document.getElementById("tag-name-warn");
function tagnameWarn(){
    if(addTagName.value===""){
        addTagNameWarn.innerHTML="标签名不能为空";
        return false;
    }else{
        addTagNameWarn.innerHTML="*";
        return true;
    }
}
function tagData(tagname,tagdescription,ishidden,title){
    addTagName.value=tagname;
    addTagInstrotiction.value=tagdescription;
    addTagIsHidden.checked = ishidden === 1;
    document.getElementsByClassName("add-tag-titleText")[0].innerHTML=title;
}
addTagName.addEventListener("input",()=>{
    if(addTagName.value!==""){
        addTagNameWarn.innerHTML="*";
    }
})
if(addTag){
    addTag.onclick=()=>{
        tagData("","",1,"添加标签")
        tc_open2(addTagTc, addTagShowmodal, "block");
    }
    [addTagCancel,addTagShowmodal,addTagclose].forEach((closeTc)=>{
        closeTc.onclick=()=>{
            tc_close2(addTagTc, addTagShowmodal);
            tagData("","",1,"添加标签")
        }
    })
    addTagConfirm.onclick=()=>{
        if(!tagnameWarn())return;
        let tagname = addTagName.value;
        let tagInstrotiction = addTagInstrotiction.value===""?"无":addTagInstrotiction.value;
        let tagIsHidden = addTagIsHidden.checked?1:0;
        window.keyWord = document.getElementById("search-tag").value;
        $.ajax({
            url:`/AdminController/tag/add?tagDescription=${tagInstrotiction}&tagName=${tagname}&tagStatus=${tagIsHidden}`,
            type:"POST",
            dataType:"text",
            contentType:"application/json",
            success: function (response) {
                showAlert("添加成功", "green");
                tc_close2(addTagTc, addTagShowmodal);
                setTimeout(() => {
                    window.location.href=`/AdminController/tag?keyword=${window.keyWord}`;
                },300);
            },
            error: function (data) {
                showAlert("标签名以存在", "red");
            }
        })
    }
}
//标签编辑
const editTag = document.querySelectorAll(".category-edit");
editTag.forEach((tag)=>{
    tag.addEventListener("click",()=>{
        const row = tag.closest("tr");
        let tagId = row.querySelector('td:nth-child(2)').textContent;
        let tagName = row.querySelector('td:nth-child(3)').textContent;
        let tagInstrotiction = row.querySelector('td:nth-child(4)').textContent;
        const isHidden = row.querySelector('td:nth-child(6)').textContent==="正常"?1:0;
        window.keyWord = document.getElementById("search-tag").value;
        tagData(tagName,tagInstrotiction,isHidden,"编辑标签");
        tc_open2(addTagTc, addTagShowmodal, "block");
        addTagConfirm.onclick=()=>{
            if(!tagnameWarn())return;
            let tagName = addTagName.value;
            let tagInstrotiction = addTagInstrotiction.value===""?"无":addTagInstrotiction.value;
            let isHidden = addTagIsHidden.checked?1:0;
            window.keyWord = document.getElementById("search-tag").value;
            $.ajax({
                url:`/AdminController/tag/edit/${tagId}?tagDescription=${tagInstrotiction}&tagName=${tagName}&tagStatus=${isHidden}`,
                type:"POST",
                dataType:"text",
                contentType:"application/json",
                success: function (response) {
                    $.ajax({
                        url: `/AdminController/tag/updateStatus?tagId=${tagId}&tagStatus=${isHidden}`,
                        type: "post",
                        dataType: "text",
                        contentType: "application/json",
                        success: function () {
                            showAlert("更改成功", "green");
                            tc_close2(addTagTc, addTagShowmodal);
                            setTimeout(() => {
                                window.location.href=`/AdminController/tag?keyword=${window.keyWord}`;
                            },300);
                        },
                        error: function (data) {
                            showAlert("编辑失败", "red");
                        }
                    })
                },
                error: function (data) {
                    showAlert("编辑失败", "red");
                }
            })
        }
    })
})
if(document.getElementById("search-hotSearch"))window.keyWord = document.getElementById("search-hotSearch").value;
//设置全选按钮
const selectAllTrending = document.getElementById("selectAllTrending");
const trendingCheckbox = document.querySelectorAll(".trendingCheckbox");
if(selectAllTrending){
    selectAllTrending.addEventListener("change",function(){
        trendingCheckbox.forEach((checkbox) => checkbox.checked = this.checked);
        console.log(1);
    },false);
}
//单个热搜删除
const deletahotSearch = document.querySelectorAll(".hot-search-delete");
const DHStc = document.getElementById("delete-hotsearch-tc");
const DHSshowModal = document.getElementById("showModal-delete-hot");
const DHSconfirm = document.getElementById("confirm-delete-hotsearch");
const DHScancel = document.getElementById("cancel-delete-hotsearch");
const DHSclose = document.getElementById("close-delete-hotsearch");
function deletehotSearch_fu(hotSearchId){
    return new Promise((resolve, reject) => {
        $.ajax({
            url: `/AdminController/hotSearch/deleteSingle/${hotSearchId}`,
            type: "POST",
            dataType: "text",
            contentType: "application/json",
            success: function () {
                resolve();
            },
            error: function () {
                reject();
            }
        })
    })
}
if(deletahotSearch){
    deletahotSearch.forEach((deletehotSearch) =>
        deletehotSearch.addEventListener("click",function(){
            const row = this.closest("tr");
            const hotSearchId = row.querySelector("td:nth-child(2)").textContent;
            tc_open2(DHStc,DHSshowModal,"block");
            [DHScancel,DHSclose,DHSshowModal].forEach((btn)=>{
                btn.onclick = function(){
                    tc_close2(DHStc,DHSshowModal);
                }
            })
            DHSconfirm.onclick =async function(){
                try{
                    await deletehotSearch_fu(hotSearchId);
                    showAlert("删除成功","green");
                    tc_close2(DHStc,DHSshowModal);
                    setTimeout(() => {
                        window.location.href=`/AdminController/hotSearch?currentPage=${window.currentPage}&pageSize=10&keyword=${window.keyWord}`
                    },300)
                }
                catch(err){
                    showAlert("删除失败","red");
                }
            }
        })
    );
}

//批量删除
function batchDeleteFun(){          //批量删除的函数
    //删除用户后的操作
    let deleteIds = [];
    const trendingCheckbox = document.querySelectorAll(".trendingCheckbox");
    for(let i=0;i<trendingCheckbox.length;i++){     //获取选中的用户的id
        if(trendingCheckbox[i].checked){
            const row = trendingCheckbox[i].closest("tr");
            let userId =row.querySelector('td:nth-child(2)').textContent;
            deleteIds.push(userId);
        }
    }
    if(deleteIds.length===0){
        showAlert("未选择要删除的用户",'red');
    }else{
        let url2=`/AdminController/hotSearch/deleteBatch/{hotSearchIds}?`;
        for(let i=0;i<deleteIds.length;i++){
            if(i===0){
                url2+=`hotSearchIds=${deleteIds[i]}`;
            }else{
                url2+=`&hotSearchIds=${deleteIds[i]}`;
            }
        }
        $.ajax({
            url:url2,
            type:'post',
            dataType:"text",
            contentType:"application/json",
            success:function(data){
                showAlert("删除成功",'green');
                tc_close2(DHStc,showModal);
                setTimeout(() => { window.location.href=`/AdminController/hotSearch?currentPage=${window.currentPage}&pageSize=10&keyword=${window.keyWord}`;},500)
            },
            error:function(){
                showAlert("删除失败",'red');
            }
        })
    }
}
const DHSbatch = document.getElementById("batch-delete-hots");
if(DHSbatch){
    DHSbatch.onclick =function(){
        tc_open2(DHStc,DHSshowModal,"block");
        [DHScancel,DHSclose,DHSshowModal].forEach((btn)=>{
            btn.onclick = function(){
                tc_close2(DHStc,DHSshowModal);
            }
        })
        DHSconfirm.onclick = function(){
            batchDeleteFun();
        }
    }
}

//confirm
function confirm(title,content){
    const confirmTitle = document.getElementById("confirm-title");
    const confirmContent = document.getElementById("article-content-span");
    confirmTitle.innerHTML = title;
    confirmContent.innerHTML = content;
}
//删除审核记录表内容
const deleteArticle = document.querySelectorAll(".delete-news");
const confirmTc = document.getElementById('confirm-container');     //confirm弹窗
const confirmBtn = document.getElementById('confirm-button');
const cancelBtn = document.getElementById('cancel-button');
const confirmShowmodal = document.getElementById('confirmShowmodal');
deleteArticle.forEach((deleteArticle)=>{
    deleteArticle.addEventListener("click",()=>{
        const row = deleteArticle.closest("tr");
        const articleId = row.querySelector('td:nth-child(2)').textContent;
        confirm("删除文章","确定删除该条记录吗？");
        tc_open2(confirmTc,confirmShowmodal,"block");
        [confirmShowmodal,cancelBtn].forEach((btn)=>{
            btn.onclick = function(){
                tc_close2(confirmTc,confirmShowmodal);
            }
        })
        confirmBtn.onclick = function(){
            window.keyWord = document.getElementById("review-form-search").value;
            $.ajax({
                url:`/AdminController/auditLog/deleteSingleAuditPost/${articleId}`,
                type:"POST",
                dataType:"text",
                contentType:"application/json",
                success:function(){
                    showAlert("删除成功",'green');
                    tc_close2(confirmTc,confirmShowmodal);
                    setTimeout(() => { window.location.href=`/AdminController/auditLog?currentPage=${window.currentPage}&pageSize=10&keyword=${window.keyWord}`;},500)
                },
                error:function(){
                    showAlert("删除失败",'red');
                }
            })
        }
    })
})
//批量删除审核内容
// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 添加输入框聚焦和失焦样式
    document.querySelectorAll('input, textarea').forEach(el => {
        el.addEventListener('focus', () => {
            el.style.borderColor = '#6b7280';
            el.style.boxShadow = '0 0 0 2px rgba(107, 114, 128, 0.1)';
        });

        el.addEventListener('blur', () => {
            if (!el.classList.contains('error')) {
                el.style.borderColor = '#d1d5db';
                el.style.boxShadow = 'none';
            }
        });
    });
});


//通用设置
function clearInput(){
    newamdinPassword.value="";
    newamdinPasswordT.value="";
    document.getElementById("admin-code").value="";
}
function restoreStyle(){
    [toSetData,toSetPrivacy].forEach(()=>{
        tosetdp.forEach((a)=>a.classList.remove("active-sdp"));
        toSetData.classList.add("active-sdp");
        document.getElementById("admin-data-set").style.display="block";
        document.getElementById('admin-privacy-set').style.display="none";
    });
    adminnewPbox.style.display="none";
    adminPasswordBox.style.display="block";
}